<!--
 * @Descripttion: 登录
 * @Author: DXV-RGWU-TUFH-RFCY-IEGMYY
 * @Date: 2020-07-06 12:17:07
 * @LastEditors: DXV-RGWU-TUFH-RFCY-IEGMYY
 * @LastEditTime: 2023-09-04 00:12:59
-->
<template>
  <div class="lb-login">
    <el-form
      @submit.native.prevent
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
      v-if="isLoad"
    >
      <div class="title-container">
        <h3 class="title">用户登录</h3>
      </div>
      <el-form-item prop="username">
        <span class="svg-container">
          <i class="iconfont icon-username"></i>
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="请输入账号"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      </el-form-item>
      <el-tooltip
        v-model="capsTooltip"
        content="Caps lock is On"
        placement="right"
        manual
      >
        <el-form-item prop="passwd">
          <span class="svg-container">
            <i class="iconfont icon-mima"></i>
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.passwd"
            :type="passwordType"
            placeholder="请输入密码"
            name="passwd"
            tabindex="2"
            autocomplete="on"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
          />
          <span class="show-pwd" @click="showPwd">
            <i
              :class="
                passwordType === 'password'
                  ? 'iconfont icon-eyeclose'
                  : 'iconfont icon-eyeopen'
              "
            />
          </span>
        </el-form-item>
      </el-tooltip>
      <el-form-item prop="codeText">
        <span class="svg-container">
          <i
            class="iconfont"
            :class="[
              { iconduanxinyanzhengma: authPhone },
              { iconemiyanzhengma: !authPhone }
            ]"
          ></i>
        </span>
        <el-input
          ref="codeText"
          v-model="loginForm.codeText"
          :placeholder="authPhone ? '请输入短信验证码' : '请输入验证码'"
          name="codeText"
          type="text"
          tabindex="3"
          autocomplete="on"
          style="width: 280px"
          @keyup.enter.native="handleLogin"
        />

        <div
          class="code-text flex-between f-desc"
          style="color: #889aa4"
          @click="toSend"
          v-if="authPhone"
        >
          <div></div>
          <div>
            {{ authTime > 0 ? `(${authTime}s)后重新获取` : `获取验证码` }}
          </div>
        </div>
        <div class="code-text" @click="refreshCode" v-if="!authPhone">
            <lb-identify
            :identifyCode="identifyCode"
            :fontSizeMin="30"
            :fontSizeMax="30"
          ></lb-identify>
        </div>
      </el-form-item>
      <el-button
        :loading="loading"
        type="primary"
        style="width: 100%; margin-bottom: 30px; height: 40px"
        @click.native.prevent="handleLogin"
        >登录</el-button
      >
    </el-form>
    <div class="lb-footer-html" v-html="fHtml"></div>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'Login',
  data () {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6 || value.length > 30) {
        callback(new Error('请输入6-30位数的密码'))
      } else {
        callback()
      }
    }
    const validateCodeText = (rule, value, callback) => {
      let { authPhone } = this
      if (value === '') {
        callback(new Error(authPhone ? '请输入短信验证码' : '请输入验证码'))
      } else if (authPhone && (!/^[0-9]+$/.test(value) || value.length !== 6)) {
        callback(new Error('请输入6位数的验证码'))
      } else if (!authPhone && (!/^[a-z0-9]+$/.test(value) || value.length !== 4)) {
        callback(new Error('请输入4位数的验证码，仅限英文小写字母或数字'))
      } else {
        callback()
      }
    }
    return {
      isLoad: false,
      authPhone: 0,
      fHtml: '',
      identifyCode: '',
      authTime: 0,
      timer: null,
      loginForm: {
        username: '',
        passwd: '',
        codeText: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: this.$reg.isNotNull, reg_type: 2, text: '账号' }],
        passwd: [{ required: true, trigger: 'blur', validator: validatePassword }],
        codeText: [{ required: true, trigger: 'blur', validator: validateCodeText }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      lockTap: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {}
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created () {
  },
  async mounted () {
    await this.getBaseInfo()
    this.isLoad = true
    setTimeout(() => {
      if (this.loginForm.username === '') {
        this.$refs.username.focus()
      } else if (this.loginForm.passwd === '') {
        this.$refs.passwd.focus()
      } else if (this.loginForm.codeText === '') {
        this.$refs.codeText.focus()
      }
    }, 100)
  },
  computed: {
    ...mapState({
      routesItem: state => state.routes
    })
  },
  methods: {
    ...mapMutations(['changeRoutesItem']),
    async getBaseInfo () {
      let [auth, config] = await Promise.all([this.$api.base.authPhone(), this.$api.base.getConfig()])
      this.authPhone = auth.data
      if (!auth.data) {
        this.makeCode()
      }
      let { record_type: type, record_no: no } = config.data
      if (!no) return
      let recordcode = type === 2 ? no.replace(/[^0-9]/ig, '') : ``
      let image = type === 1 ? `` : `<image class="mr-sm" src="https://lbqny.migugu.com/admin/public/information.png"></image>`
      let href = type === 1 ? `https://beian.miit.gov.cn/` : `https://www.beian.gov.cn/portal/registerSystemInfo?recordcode=${recordcode}`
      this.fHtml = `<div class="flex-y-center c-base">备案号：${image} <a class="c-base" href="${href}" target="_blank">${no}</a></div>`
    },
    checkCapslock ({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if ((shiftKey && (key >= 'a' && key <= 'z')) || (!shiftKey && (key >= 'A' && key <= 'Z'))) {
          this.capsTooltip = true
        } else {
          this.capsTooltip = false
        }
      }
      if (key === 'CapsLock' && this.capsTooltip === true) {
        this.capsTooltip = false
      }
    },
    showPwd () {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    setCookie (cname, cvalue, exdays) {
      var d = new Date()
      d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000))
      var expires = 'expires=' + d.toGMTString()
      document.cookie = `${cname}=${cvalue};${expires};`
    },
    refreshCode () {
      this.makeCode()
    },
    makeCode () {
      this.identifyCode = Math.random().toString(36).substr(2, 4)
      this.setCookie('codeText', this.identifyCode, 3)
    },
    toClearTimer () {
      this.authTime = 0
      clearInterval(this.timer)
    },
    // 发送验证码
    async toSend () {
      let {
        authTime
      } = this
      if (authTime) return
      let {
        username,
        passwd
      } = this.loginForm
      username = username ? username.replace(/(^\s*)|(\s*$)/g, '') : ''
      if (!username) {
        this.$message.error(`请输入账号`)
        return
      }
      if (passwd.length < 6 || passwd.length > 30) {
        this.$message.error(`请输入6-30位数的密码`)
        return
      }
      let param = this.$util.pick(this.loginForm, ['username', 'passwd'])
      if (this.lockTap) return
      this.lockTap = true
      try {
        let { code, data } = await this.$api.base.sendAuthCode(param)
        this.lockTap = false
        this.loginForm.codeText = ''
        if (code !== 200) return
        this.$message.success(`已向 ${data} 发送短信验证码，请注意查收`)
        let time = 60
        this.timer = setInterval(() => {
          if (time === 0) {
            this.toClearTimer()
            return
          }
          time--
          this.authTime = time
        }, 1000)
      } catch (e) {
        setTimeout(() => {
          this.lockTap = false
        }, 2000)
      }
    },
    handleLogin () {
      // if (process.env.NODE_ENV === 'development') {
      //   // let res = { "data": { "user": { "id": 109, "uniacid": 666, "username": "张三", "passwd": "d23a457be84ab338c2f6bca4954a3673", "create_time": 1678696895, "is_admin": 2, "balance": 0, "user_id": 0, "status": 1, "passwd_text": "123456", "cash": 0, "lock": 0, "city_type": 1, "admin_pid": 0, "level_balance": 0, "city_id": 0, "province": "", "phone": "" }, "token": "fafea92767e540988e885b39fe3dd71e" }, "code": 200, "sign": null }
      //   let res = { "data": { "user": { "id": 1, "uniacid": 666, "username": "admin", "passwd": "7214bd4a24659d3d5915fa9e62c548e6", "create_time": 1625585405, "is_admin": 1, "balance": 0, "user_id": 0, "status": 1, "passwd_text": "", "cash": 0, "lock": 0, "city_type": 1, "admin_pid": 0, "level_balance": 0, "city_id": 0 }, "token": "5124849f34f14d6daa2e51050e15ca0a" }, "code": 200, "sign": null }
      //   // let res = { "data": { "user": { "id": 93, "uniacid": 666, "username": "自己猜(请不要删除和修改)", "passwd": "d23a457be84ab338c2f6bca4954a3673", "create_time": 1677824966, "is_admin": 0, "balance": 10, "user_id": 708, "status": 1, "passwd_text": "123456", "cash": 80.7, "lock": 3, "city_type": 3, "admin_pid": 0, "level_balance": 0, "city_id": 158, "province": "", "phone": "13649491212" }, "token": "1da056a2d75045a88ddd013ef60f8540" }, "code": 200, "sign": null }
      //   // let res = { "data": { "user": { "id": 124, "uniacid": 666, "username": "向日葵", "passwd": "d23a457be84ab338c2f6bca4954a3673", "create_time": 1679898785, "is_admin": 0, "balance": 12, "user_id": 831, "status": 1, "passwd_text": "123456", "cash": 4.8, "lock": 0, "city_type": 1, "admin_pid": 123, "level_balance": 12, "city_id": 28, "province": "", "phone": "13649151212", "agent_name": "向日葵" }, "token": "139670f8bdda4fae88b1f4f797897b04" }, "code": 200, "sign": null }
      //   // let res = { "data": { "user": { "id": 140, "uniacid": 666, "username": "xiaoli", "passwd": "d23a457be84ab338c2f6bca4954a3673", "create_time": 1680486689, "is_admin": 0, "balance": 10, "user_id": 824, "status": 1, "passwd_text": "123456", "cash": "1811.80", "lock": 2, "city_type": 1, "admin_pid": 0, "level_balance": 0, "city_id": 28, "province": "", "phone": "18232288888", "agent_name": "这是萧萧的代理商真实姓名啊啊啊啊啊啊啊啊", "agreement": "https:\/\/lbqnyv3.migugu.com\/file\/666\/23\/05\/zTeYL7XxJObwU2bBK8HM05SUtUG35nGr.docx", "agreement_title": "代理商xx的合同", "phone_admin_num": 0, "phone_encryption": 0, "salesman_auth": 1, "channel_auth": 1, "partner_auth": 1, "license": "https:\/\/lbqnyv3.migugu.com\/image\/666\/23\/06\/vN2TficK6sYzrnNipTbn7AicAN9PuImk.webp", "agreement_time": 1, "check_cash": "0.00", "merchant_name": "啊啊啊啊啊啊啊啊这里是名字很长的商家名称", "signature_content": "成都龙兵科技有限公司" }, "token": "8a7ccb4f345a4c92b8c48f19adb3b2b4" }, "code": 200, "sign": null }
      //   this.changeRoutesItem({ key: 'userInfo', val: res.data.user })
      //   window.localStorage.setItem('massage_minitk', res.data.token)
      //   window.localStorage.setItem('massage_ms_username', res.data.user.username)
      //   window.localStorage.setItem('massage_userInfo', JSON.stringify(res.data.user))
      //   this.$router.push('/')
      // } else {
        this.loading = true
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            if (this.timer) this.toClearTimer()
            let param = JSON.parse(JSON.stringify(this.loginForm))
            if (this.authPhone) {
              param.short_code = param.codeText
              delete param.codeText
            }
            this.$api.base.login(param).then(res => {
              this.loading = false
              if (res.code === 200) {
                this.changeRoutesItem({ key: 'userInfo', val: res.data.user })
                window.localStorage.setItem('massage_minitk', res.data.token)
                window.localStorage.setItem('massage_ms_username', res.data.user.username)
                window.localStorage.setItem('massage_userInfo', JSON.stringify(res.data.user))
                this.$router.push('/')
              } else {
                this.refreshCode()
              }
            })
          } else {
            this.loading = false
            return false
          }
        })
      // }
    },
    getOtherQuery (query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>

<style lang="scss">
$bg: #283443;
$light_gray: #fff;
$cursor: #fff;
@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .lb-login .el-input input {
    color: $cursor;
  }
}
/* reset element-ui css */
.lb-login {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;
      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }
  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
  .el-form-item__content {
    line-height: 34px;
  }
}

.lb-footer-html {
  width: 100%;
  height: 49px;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
  font-size: 13px;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
.lb-login {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }
  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }
  .title-container {
    position: relative;
    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }
  .code-text {
    width: 160px;
    height: 40px;
    position: absolute;
    right: 9px;
    bottom: 5px;
    cursor: pointer;
  }
  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>
